<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Library\Response;
use App\Http\Models\ZtkUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Validator;
use Overtrue\EasySms\EasySms;
use Illuminate\Support\Facades\Cache;

class AuthController extends Controller
{
    /*
     * 登陆
     */
    public function showLogin()
    {
        return view('web.auth.login');
    }

    public function login(Request $request)
    {
        // 规则
        $rules = [
            'mobile' => 'required|regex:/^1[23456789]\d{9}$/',
            'password' => 'required'
        ];
        Auth::logout();
        // 自定义消息
        $messages = [
            'mobile.required' => '请输入手机号',
            'mobile.regex'=>'手机号码格式不正确',
            'password.required' => '请输入密码'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            return Response::response(['code' => Response::PARAM_ERROR, 'msg' => $validator->errors()->first()]);
        }

        $mobile = $request->input('mobile');
        $password = $request->input('password');

        $exists = ZtkUser::banStatus()->where('mobile',$mobile)->exists();
        if($exists) return Response::response(['code' => Response::PARAM_ERROR, 'msg' => '账户违规操作被封,请联系管理员解封！']);

        if (!Auth::attempt(['mobile' => $mobile, 'password' => $password])) {
            return Response::response(['code' => Response::PARAM_ERROR, 'msg' => '手机号或密码有误']);
        }
        return Response::response(['code' => Response::OK, 'msg' => '登录成功','data' => ['action' => route('index')]]);
    }

    public function showRegister()
    {
        return view('web.auth.register');
    }

    public function register(Request $request)
    {
        // 规则
        $rules = [
            'mobile' => 'required|regex:/^1[23456789]\d{9}$/|unique:ztk_user',
            'code' => 'required',
            'password' => 'required|confirmed',
            'password_confirmation' => 'required',
        ];

        // 自定义消息
        $messages = [
            'mobile.required' => '请输入手机号',
            'mobile.regex' => '手机号码格式不正确',
            'mobile.unique' => '手机号已存在',
            'code.required' => '请输入验证码',
            'password.required' => '请输入密码',
            'password_confirmation.required' => '请输入确认密码',
            'password.confirmed' => '两次输入密码不一致',
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            return Response::response(['code' => Response::PARAM_ERROR, 'msg' => $validator->errors()->first()]);
        }

        try {
            $input = $request->all();

            $key = 'reg_code_'.$input['mobile'];
            if(!Cache::has($key)) {
                return Response::response(['code' => Response::PARAM_ERROR, 'msg' => '短信验证码不正确']);
            }
            $verifyData = Cache::get($key);
            if($verifyData['code'] != $input['code']){
                return Response::response(['code' => Response::PARAM_ERROR, 'msg' => '短信验证码不正确']);
            }

            $user = new ZtkUser();
            $user->name       = $input['mobile'];
            $user->mobile     = $input['mobile'];
            $user->password   = bcrypt($input['password']);
//            $user->union_name = $input['union_name'];
//            $user->union_desc = $input['union_desc'];
            $user->save();

            Auth::login($user); // 注册的用户让其进行登陆状态

            return Response::response(['code' => Response::OK, 'msg' => '注册成功','data' => ['action' => route('index')]]);
        } catch (QueryException $e) {
            return Response::response(['code' => Response::SQL_ERROR, 'msg' => '注册失败']);
        }
    }


    /*
     * 退出登录
     */
    public function logout()
    {
        Auth::logout();
        return redirect(route('index'));
    }

    /**
     * 发送短信验证码
     * https://github.com/overtrue/easy-sms
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     */
    public function sendSms(Request $request)
    {
        // 规则
        $rules = [
            'mobile' => 'required|regex:/^1[23456789]\d{9}$/|unique:ztk_user',
        ];
        // 自定义消息
        $messages = [
            'mobile.required' => '请输入手机号',
            'mobile.regex'    => '手机号码格式不正确',
            'mobile.unique'   => '手机号已存在，请登录',
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            return Response::response(['code' => Response::PARAM_ERROR, 'msg' => $validator->errors()->first()]);
        }

        $mobile = $request->input('mobile');
        $key = 'reg_code_'.$mobile;
        $num = 1;
        if(Cache::has($key)) {
            $verifyData = Cache::get($key);
            if($verifyData['num'] > 3){
                return Response::response(['code' => Response::PARAM_ERROR, 'msg' => '发送频繁,请稍后再试']);
            }
            $num = $verifyData['num'] + 1;
        }

        try {
            $code = mt_rand(100000,999999);
            Cache::put($key,['mobile' => $mobile,'code' => $code,'num' => $num],600);//十分钟 单位秒

            $config = config('easysms');
            $easySms = new EasySms($config);
            $easySms->send($mobile, [
                'template' => 'SMS_180351023',
                'data' => [
                    'code' => $code
                ],
            ]);

            return Response::response(['code' => Response::OK, 'msg' => '发送成功']);

        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
//            $message = $exception->getException('aliyun')->getMessage();
//            dd($message);
            return Response::response(['code' => Response::BAD_REQUEST, 'msg' => '发送失败，请重试']);
        }
    }
}
